package xyz.myachin.saveto.ui.sharing.supports

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import xyz.myachin.saveto.R
import xyz.myachin.saveto.logic.NDA
import xyz.myachin.saveto.logic.intent.ACTION_NEED_DOWNLOAD
import xyz.myachin.saveto.settings.Settings

class NeedDownloaderActivity : AppCompatActivity(), View.OnClickListener {
    private lateinit var mBtOpen: Button
    private lateinit var mBtAlwaysAsText: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_need_downloader)

        fillUI(intent)
    }

    private fun fillUI(intent: Intent?) {
        when (intent?.action) {
            ACTION_NEED_DOWNLOAD -> {
                val tv = findViewById<TextView>(R.id.tvExplain)
                mBtOpen = findViewById(R.id.btOpenMarket)
                mBtAlwaysAsText = findViewById(R.id.btAlwaysAsText)

                tv.text = getString(R.string.need_downloader_message, getString(R.string.app_name))

                mBtOpen.setOnClickListener(this)
                mBtAlwaysAsText.setOnClickListener(this)
            }
            else -> {
                Log.e(NDA, "fillUI: unexpected intent action: ${intent?.action}")
                finishAsCancel()
            }
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            mBtOpen.id -> {
                Intent(Intent.ACTION_VIEW).also { market ->
                    market.action = Intent.ACTION_VIEW
                    market.data = Uri.parse("market://details?id=xyz.myachin.downloader")
                    setResult(RESULT_OK, market)
                }
                finish()
            }
            mBtAlwaysAsText.id -> {
                Settings.useDownloader = false
                finishAsCancel()
            }
            else -> {
                Log.e(NDA, "onClick: unexpected view id")
                finishAsCancel()
            }
        }
    }

    private fun finishAsCancel() {
        setResult(RESULT_CANCELED)
        finish()
    }
}